package com.sf.common;

import com.sf.exception.ParamException;
import com.sf.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {

    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        String url = request.getRequestURI();
        ModelAndView mv;
        String defaultMsg = "System error";
        JsonData result;

        //.json ,.page

        if (url.endsWith("json")) {//强制要求项目请求json数据，都以.json结尾
            if (ex instanceof PermissionException || ex instanceof ParamException) {
                result = JsonData.fail(ex.getMessage());
                mv = new ModelAndView("jsonView exception", result.toMap());
            } else {
                log.error("unknow json exception" + url + ex);
                result = JsonData.fail(defaultMsg);
                mv = new ModelAndView("jsonView", result.toMap());
            }
        } else if (url.endsWith(".page")) {//强制要求项目请求page页面，都以.page结尾
            log.error("unknow page exception" + url + ex);
            result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception", result.toMap());
        } else {
            log.error("unknow exception" + url + ex);
            result = JsonData.fail(defaultMsg);
            mv = new ModelAndView("exception", result.toMap());
        }
        return mv;
    }
}
